<?php	
include("../mysql_connect.php");
include("../error/upload.php");
include("../Email/PHPMailer/class.phpmailer.php");
// Get XML
/*	
	$xmlCreate = '
<ShareGroup UserName="rafale@thetigerparty.com" GroupID="" GroupName="Family" Method="Create">
</ShareGroup>';
	$xmlModify = '
<ShareGroup UserName="rafale@thetigerparty.com" GroupID="32" GroupName="Family" Method="Modify" newName="MyFamily">
	<User ID="4" Name="MemberA" Email="a@family.com"/>
	<User ID="5" Name="MemberB" Email="b@family.com"/>
	<User ID="6" Name="MemberCC" Email="c@family.com"/>
	<User ID="7" Name="MemberD" Email="d@family.com"/>
	<User ID="" Name="MemberE" Email="e@family.com"/>
	<User ID="" Name="MemberF" Email="f@family.com"/>
</ShareGroup>';
	$xmlDelete = '
<ShareGroup UserName="rafale@thetigerparty.com" GroupID="32" GroupName="Family" Method="Delete"/>';

	$xml = simplexml_load_string($xmlDelete);
/*/
	$xml = simplexml_load_file('php://input');
//*/
	// Get ShareGroupAttr
	$GroupAttr = array();
	foreach( $xml->attributes( ) as $attr)
	{
		$GroupAttr[] = (string)$attr;
	}
	
	// Get User FirstName
	$FirstName = $GroupAttr[1];	
	
	// Get User ID
	$UserID = GetUsersID($FirstName, array(array(0,0,$GroupAttr[0])));	
	
	
	// Ger Group IF
	$GroupID = $GroupAttr[2];
	 
	switch ( $Method = $GroupAttr[4] )
	{
	case "Create":
		// Create Group ( GroupName, UserID )
		$GroupID = CreateGroup( $GroupAttr[3], $UserID[0] );
		
		
		// Get All Members
		$NewMembers = array();
		$MembersList = array();
		foreach( $xml->children( ) as $Member)
		{
			$newMember = array();
			foreach( $Member->attributes() as $attr)
			{
				$newMember[] = (string)$attr;				
			}
			if( strlen($newMember[0]) > 0 )
				$MembersList[] = $newMember;
			else
				$NewMembers[] = $newMember;
		}
		// Has New members
		if( count( $NewMembers ) > 0 )
		{
			$MemberID = GetUsersID($FirstName, $NewMembers );
			for( $i = 0 ; $i < count( $NewMembers ) ; $i++ )
			{
				$NewMembers[$i][0] = $MemberID[$i];
			}
			$MembersList = array_merge( $NewMembers, $MembersList);
		}
		// Add Member
//		if( count($MembersList) )
			AddMemberGroup( $GroupID, $UserID[0], $MembersList );
		
		
		ResponseXML( $GroupID, $GroupAttr[3]);
		break;
	case "Modify":
		// if has newName
		if( isset($GroupAttr[5]) && strlen($GroupAttr[5]) > 0)
		{
			// Rename ( GroupID, UserID, newNamw )
			RenameGroup( $GroupID, $UserID[0], $GroupAttr[5] );
		}
		
		// Get All Members
		$NewMembers = array();
		$MembersList = array();
		foreach( $xml->children( ) as $Member)
		{
			$newMember = array();
			foreach( $Member->attributes() as $attr)
			{
				$newMember[] = (string)$attr;				
			}
			if( strlen($newMember[0]) > 0 )
				$MembersList[] = $newMember;
			else
				$NewMembers[] = $newMember;
		}
		// Has New members
		if( count( $NewMembers ) > 0 )
		{
			$MemberID = GetUsersID($FirstName, $NewMembers );
			for( $i = 0 ; $i < count( $NewMembers ) ; $i++ )
			{
				$NewMembers[$i][0] = $MemberID[$i];
			}
			$MembersList = array_merge( $NewMembers, $MembersList);
		}
		// Add Member
//		if( count($MembersList) )
			AddMemberGroup( $GroupID, $UserID[0], $MembersList );
			
		ResponseXML( $GroupID, $GroupAttr[5]);

		break;
	case "Delete":
		if(CheckGroupExist($GroupID))
			DeleteGroup( $GroupID );
		echo '<ShareGroup GroupID="'.$GroupAttr[2].'" GroupName="'.$GroupAttr[3].'" Status="Delete" />';
		break;
	default:
		echo '<Error Message="The requested Information was not support" Domain="ShareGroup"/>';
		saveError("ShareGroup", NULL, date("Y-m-d H:i:s"), "The requested Information was not support");
		exit;
	}

function CreateGroup( $GroupName, $OwnerID )
{
//	$strSqlCommand = 'SELECT idGROUP FROM sharegroup WHERE Name = "'.$GroupName.'"';
//	if (! $result = mysql_query($strSqlCommand))
// 	{
//	 	echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
//		exit;
// 	}
//	if( mysql_num_rows($result) == 0)
//	{
		// Add sharegroup
		$strSqlCommand = "INSERT INTO sharegroup ( Name, USER_idUSER) 
							VALUES (\"$GroupName\", $OwnerID)";

		if (!mysql_query($strSqlCommand))
 		{
	 		echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
			saveError("CreateGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
			exit;
 		}
		// Get New Group ID
		return mysql_insert_id();
//	}
//	else
//	{
//		echo "<Error Message=\"Group Already Exist\" Domain=\"CreateGroup\" />";
//		exit;
//	}	
}
function CheckGroupExist( $GroupID )
{
	// Check Group Exist
	$strSqlCommand = 'SELECT idGROUP FROM sharegroup WHERE idGROUP = '.$GroupID;
	if (! $result = mysql_query($strSqlCommand))
 	{
	 	echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
	 	echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		saveError("CheckGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
		exit;
 	}
	if( mysql_num_rows($result) > 0)
	{
		return true;
	}
	else
	{
		echo "<Error Message=\"Group does not exist\" Domain=\"CreateGroup\" />";
		saveError("CheckGroup", NULL, date("Y-m-d H:i:s"), "Group does not exist");
		exit;
	}		
}
function RenameGroup( $GroupID, $OwnerID, $newName )
{
	$strSqlCommand = 'UPDATE sharegroup SET Name="'.$newName.'" WHERE idGROUP = '.$GroupID;
	if (! $result = mysql_query($strSqlCommand))
 	{
	 	echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
		 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		saveError("RenameGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
	exit;
 	}	
}
function AddMemberGroup( $GroupID, $OwnerID, $ArrayMember )
{
//	$ArrayID = GetUsersID( $ArrayMember );
	// foreach Member add spot_user_group(group, Member)
	RemoveMemberGroup($GroupID);
	
	if( count($ArrayMember) )
	{
	$strSqlCommand = "INSERT INTO spot_group_users (USER_idUSER,GROUP_idGROUP) VALUES ";

	foreach( $ArrayMember as $Member )
	{	
		$strSqlCommand .= "(".$Member[0].",".$GroupID."),";
	}
	
	if (!mysql_query(substr($strSqlCommand,0,-1)))
	{
		echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		saveError("AddMemberGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
		exit;
	}
	}
}
function RemoveMemberGroup( $GroupID )
{
	// foreach RemoveMember remove spot_user_group(group, RemoveMember)
	$strSqlCommand = "DELETE FROM spot_group_users WHERE GROUP_idGROUP = ". $GroupID;

	if (!mysql_query($strSqlCommand))
	{
		echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		saveError("RemoveMemberGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
		exit;
	}	
}
function DeleteGroup( $GroupID )
{
	// foreach Member remove spot_user_group(group)	
	$strSqlCommand = 'DELETE FROM spot_group_users
					  WHERE GROUP_idGROUP = '.$GroupID; 			
	if (!mysql_query($strSqlCommand))
	{
		echo "<Error Message=\"spot_group_users:".mysql_error()."\" Domain=\"DeleteGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		saveError("DeleteMemberGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
		exit;
 	}		
	
	// foreach Member remove spot_sb_group(group)	
	$strSqlCommand = 'DELETE FROM spot_group_media_sb
					  WHERE GROUP_idGROUP = '.$GroupID; 			

	if (!mysql_query($strSqlCommand))
	{
		echo "<Error Message=\"spot_group_media_sb:".mysql_error()."\" Domain=\"DeleteGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		saveError("DeleteMemberGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
		exit;
 	}	

	// Remove Group		
	$strSqlCommand = 'DELETE FROM sharegroup
					  WHERE idGROUP = '.$GroupID; 			

	if (!mysql_query($strSqlCommand))
	{
		echo "<Error Message=\"sharegroup:".mysql_error()."\" Domain=\"DeleteGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
			saveError("DeleteMemberGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
		exit;
 	}	
}

function GetUsersID( $FirstName, $ArrayUser )
{
	$IDs = array();
	
	foreach( $ArrayUser as $account ) 
	{
		$strSqlCommand = "SELECT idUSER FROM user WHERE Email=\"$account[2]\" ";
		if (!$result = mysql_query($strSqlCommand))
 		{
	 		echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
			saveError("GetUserGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
			exit;
 		}
		// New User Create New User
		else if( mysql_num_rows( $result) == 0 )
		{
			
			// Add New User
			$strSqlCommand = "INSERT INTO user ( Name, Email, Enable) 
								VALUES (\"$account[1]\", \"$account[2]\", 0)";
	
			if (!mysql_query($strSqlCommand))
			{
				echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
				echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
				saveError("InsertUserGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
				exit;
			}
			// Get New User ID
			$IDs[] = mysql_insert_id();
			
		$mail = new PHPMailer(); 				//New instance, with exceptions enabled		
		$mail->IsSMTP();                        // tell the class to use SMTP
		$mail->SMTPAuth   = true;               // enable SMTP authentication
			
		$mail->SMTPSecure = "ssl";
		$mail->Port       = 465;                // set the SMTP server port
		$mail->Host       = "smtp.gmail.com";   // SMTP server
		$mail->Username   = "info@bespoke-app.com";     // SMTP server username
		$mail->Password   = "gobespoke";                // SMTP server password
		
		$mail->From       = "info@bespoke-app.com";
		$mail->FromName   = "Bespoke";
		
		$mail->Subject  = "Join my group on Bespoke.";
	
		$mail->AddAddress($account[2]);
		$mail->Body = "Hi ".$account[1].",<p>I am inviting you to share my Inspiration Book on Bespoke with you. Bespoke is a Social Media Atelier which you might like. <a href=''>Check it out</a></p><p>Cheers,</p>".$FirstName."";
			
		$mail->IsHTML(true);      
			if(!$mail->Send()) {
				echo "<Error Message=\"". $mail->ErrorInfo."\" Domain=\"CreateGroup\"/>";
				SaveError("InsertUserGroup", NULL, date("Y-m-d H:i:s"), $mail->ErrorInfo);
			}
		}
		else
		{
			$row = @mysql_fetch_array($result);
			$IDs[] = $row['idUSER'];
		}
	}
	return $IDs;
/*	
	foreach( $ArrayUser as $account ) 
	{
		$strSqlCommand .= " OR Email=\"$account[1]\" ";
	}

	if (!$result = mysql_query($strSqlCommand))
 	{
	 	echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		exit;
 	}
	else
	{
		$IDs = array();
		while($row = @mysql_fetch_array($result))
		{
			$IDs[] = $row['idUSER'];
		}
		return $IDs;
	}
*/
}

function ResponseXML( $GroupID, $GroupName)
{
	$strSqlCommand = "SELECT idUSER, Name, Email FROM user
						LEFT JOIN spot_group_users ON user.idUSER = spot_group_users.USER_idUSER
						WHERE GROUP_idGROUP = $GroupID";//, Enable
	
	if (!$result = mysql_query($strSqlCommand))
 	{
	 	echo "<Error Message=\"".mysql_error()."\" Domain=\"CreateGroup\" />";
	 		echo "<Error Message=\"".$strSqlCommand."\" Domain=\"CreateGroup\" />";
		saveError("GetGroup", NULL, date("Y-m-d H:i:s"), mysql_error());
		exit;
 	}
	else
	{
		echo "<ShareGroup GroupID=\"$GroupID\" GroupName=\"$GroupName\" Status=\"Success\">";
		while($row = @mysql_fetch_array($result))
		{
			
			echo '<User ID="'.$row['idUSER'].'" Name="'.$row['Name'].'" Email="'.$row['Email'].'" ></User>';//Enable="'.$row['Enable'].'"
		}
		echo "</ShareGroup>";
	}	
}
// Backup check is Group Exist
	//SELECT idGROUP FROM spot_sb_group tb1
	//LEFT JOIN sharegroup tb2 ON tb1.GROUP_idGROUP = tb2.idGROUP
	//WHERE USER_idUSER = $GroupOwner
	//AND idGROUP IS NOT NULL
	//AND Name = $GroupName
	//GROUP BY GROUP_idGROUP
// Backup Create Group Owner
	//INSERT spot_sb_group( GROUP_idGROUP,STORYBOARD_idSTORYBOARD,USER_idUSER )	VALUE( $NewGroupID, 0, $GroupOwnerID)
?>